<template>
  <div id="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
        <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false"></el-alert>
        <el-row>
            <span>选择商品分类:</span>
            <el-cascader
                v-model="selectedKeys"
                :options="catelist"
                :props="cascProp"
                clearable
                filterable
                @change="parentCateChange">
                </el-cascader>
        </el-row>

        <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="动态参数" name="many">
                <el-button size="small" :disabled="isBtnDisable" type="primary" @click="showDialog(null)">添加参数</el-button>
                <el-table :data="manyTable" border stripe>
                    <el-table-column type="expand" label="#">
                        <template slot-scope="scope">
                        <el-tag
                        v-for="(item, i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="handleClose(i,scope.row)"
                        >{{item}}</el-tag>

                        <!-- 输入框 -->
                        <el-input
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        class="input-new-tag"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>

                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>

                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column  label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column  label="操作" prop="attr_name">
                        <template slot-scope="scope">
                            <el-button type="primary" size="small" @click="showDialog(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="remove(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button size="small" :disabled="isBtnDisable" type="primary" @click="showDialog(null)">添加属性</el-button>

                <el-table :data="onlyTable" border stripe>
                    <el-table-column type="expand" label="#">
                        <template slot-scope="scope">
                        <el-tag
                        v-for="(item, i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="handleClose(i,scope.row)"
                        >{{item}}</el-tag>

                        <!-- 输入框 -->
                        <el-input
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        class="input-new-tag"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>

                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>

                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column  label="属性名称" prop="attr_name"></el-table-column>
                    <el-table-column  label="操作" prop="attr_name">
                        <template slot-scope="scope">
                            <el-button type="primary" size="small" @click="showDialog(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="remove(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        @close="closeDialog"
        width="30%">

        <el-form ref="paramForm" :model="paramForm" :rules="paramFormRules" label-width="80px">
        <el-form-item :label="paramForm.lable" prop="attr_name">
            <el-input v-model="paramForm.attr_name"></el-input>
        </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'params',
  data() {
      return {
          catelist:[],
          selectedKeys:{},
          cascProp:{
              value:'cat_id',
              label:'cat_name',
              children:'children'
          },
          activeName:'many',
          manyTable:[],
          onlyTable:[],
          dialogVisible:false,
          dialogTitle:'',
          formLable:'',
          paramForm:{
              attr_id:0,
              lable:'',
              attr_name:''
          },
          opreator:0,
          paramFormRules:{
             attr_name:[{required: true, message: '请输入内容', trigger: 'blur' }] 
          }
      }
  },
  created(){
      this.getCateList()
  },
  computed:{
      isBtnDisable(){
          if(this.selectedKeys.length!==3){
              return true
          }
          return false
      },
      cateId(){
          if(this.selectedKeys.length==3){
              return this.selectedKeys[2]
          }
          return null
      }
  },
  methods:{
      parentCateChange(){
          this.getParams()
      },
      //根据分类ID查询动态或者静态数据
      async getParams(){
            if(this.selectedKeys.length!=3){
                this.selectedKeys={}
                return
            }
            //   根据分类ID来获取参数
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
            if(res.meta.status!==200){
                return this.$message.error(res.meta.msg)
            }
            res.data.forEach(item=>{
                 item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                //  控制每一行的文本框的显示与隐藏
                item.inputVisible=false
                // 文本框里面的值
                item.inputValue=''
            })
            if(this.activeName=='many'){
                this.manyTable=res.data
            }else{
                this.onlyTable=res.data
            }
      },
      async getCateList(){
           const{data:res}=await this.$http.get('categories')
          if(res.meta.status!=200){
              return this.$message.error(res.meta.msg)
          }
          this.catelist=res.data
      },
      handleClick(){
          this.getParams()
      },
      showDialog(data){
          if(this.activeName=='many'){
              if(data==null){
                this.dialogTitle='添加动态参数'
                this.paramForm.lable='动态参数'
              }else{
                this.opreator=1
                this.paramForm.attr_id=data.attr_id
                this.paramForm.attr_name=data.attr_name
                this.dialogTitle='编辑动态参数'
                this.paramForm.lable='动态参数'
              }
              
          }else{
              if(data==null){
                this.dialogTitle='添加静态属性'
                this.paramForm.lable='静态属性'
              }else{
                this.opreator=1
                this.paramForm.attr_id=data.attr_id
                this.paramForm.attr_name=data.attr_name
                this.dialogTitle='编辑静态属性'
                this.paramForm.lable='静态属性'
              }
          }
          this.dialogVisible=true
      },
      closeDialog(){
          this.dialogTitle=''
          this.paramForm.attr_id=0
          this.paramForm.lable=''
          this.paramForm.attr_name=''
          this.opreator=0
          this.dialogVisible=false
      },
      save(){
          if(this.opreator==0){
              this.add()
          }else{
              this.edit()
          }
      },
      add(){
          this.$refs.paramForm.validate(async valid=>{
              if(!valid) return
                 const{data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,
                 {
                     attr_name:this.paramForm.name,
                     attr_sel:this.activeName

                 })
                 if(res.meta.status!=201){
                     return this.$message.error(res.meta.msg)
                 }
                 this.$message.success(res.meta.msg)
                 this.getParams()
                 this.dialogVisible=false
             })
      },
      edit(){
          this.$refs.paramForm.validate(async valid=>{
               if(!valid) return
                 const{data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.paramForm.attr_id}/`,
                 {
                     attr_name:this.paramForm.attr_name,
                     attr_sel:this.activeName

                 })
                 if(res.meta.status!=200){
                     return this.$message.error(res.meta.msg)
                 }
                 this.$message.success(res.meta.msg)
                 this.getParams()
                 this.dialogVisible=false
             })
      },
      async remove(id){
           const result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            if(result=='confirm'){
                const{data:res}=await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
                if(res.meta.status==200){
                    this.$message({type: 'success',message: '删除成功!'})
                    this.getParams()
                }else{
                    return this.$message.error(res.meta.msg)
                }       
            }
      },
      async saveAttrVals(row){
          const{data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}/`,
                 {
                     attr_name:row.attr_name,
                     attr_sel:row.attr_sel,
                     attr_vals:row.attr_vals.join(' ')
                 })
                 if(res.meta.status!=200){
                     return this.$message.error(res.meta.msg)
                 }
                 this.$message.success(res.meta.msg)
      },
      async handleInputConfirm(row){
          if(row.inputValue.trim().length==0){
              row.inputValue=''
              row.inputVisible=false
              return
          }
          row.attr_vals.push(row.inputValue.trim())
          row.inputValue=''
          row.inputVisible=false
        // 保存
          this.saveAttrVals(row)
      },
      showInput(row){
          row.inputVisible=true
          this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
        })
      },
      handleClose(index,row){
          row.attr_vals.splice(index,1)
          this.saveAttrVals(row)
      }
  }
}
</script>

<style scoped>
.el-row{
    margin: 15px;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
  }
</style>>

</style>
